/**
 * Project Name:pay-core
 * File Name:ToolUtil.java
 * Package Name:cn.swiftpass.utils.paycore
 * Date:2014年10月30日下午1:58:45
 *
 */

package com.ibeetl.admin.aod.util;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ClassName:ToolUtil Function: 工具帮助类 Date: 2014年10月30日 下午1:58:45
 * 
 * @author 陈鹏
 */
public class ToolUtil {

    public static final String MOENYUNIT = "人民币"; // 金钱单位

    public static final int YUAN_TO_FEN_RATE = 100;// 元和分转换的费率

    /**
     * getEnd:获取结束时间 (如果开始时间和结束时间为同一天直接返回结束时间，如果不为同一天返回结束时间去掉时分秒)
     * 
     * @author 陈鹏
     * @param begin
     * @param end
     * @return
     */
    public static Date getEnd(Date begin, Date end) {
        // 需要判断 是否是第二天，如果是，则取第二天 00:00:00
        if (getDay(begin) != getDay(end)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(end);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            return calendar.getTime();
        }
        return end;
    }

    /**
     * @author 陈鹏 这里还需要判断 当前时间 减去5 分钟后是否是昨天
     * @param begin
     * @param end
     * @return
     */
    public static Date getBegin(Date begin, Date end) {

        if (end != null) {
            return end;
        }
        if (begin == null) {
            begin = new Date();
        }

        // int day = getDay(begin);
        // if (end == null) {
        // end = begin;
        // }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(begin);
        // calendar.add(Calendar.MINUTE, -5);

        // 如果 天数不相同 则属于跨天
        //
        // if (day != getDay(calendar.getTime())) {
        // calendar.add(Calendar.MINUTE, 5);
        // calendar.set(Calendar.HOUR_OF_DAY, 0);
        // calendar.set(Calendar.MINUTE, 0);
        // calendar.set(Calendar.SECOND, 0);
        // calendar.set(Calendar.MILLISECOND, 0);
        // }

        return calendar.getTime();
    }

    /**
     * getDay:获取时间 是哪天
     * 
     * @author 陈鹏
     * @param date
     * @return
     */
    public static int getDay(Date date) {
        if (date == null) {
            date = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * comparetDate:比较时间 是否是在同一分钟
     * 
     * @author 陈鹏
     * @return
     */
    public static boolean comparetDateYMDHM(Date begin, Date end) {
        if (begin == null || end == null) {
            return false;
        }
        long beginM = begin.getTime() / 60000;
        long endM = end.getTime() / 60000;
        if (beginM == endM) {
            return true;
        }
        return false;
    }

    /**
     * strToDate: 日期格式 默认 yyyy-MM-dd HH:mm:ss
     * 
     * @param date
     * @return
     */
    public static Date strToDate(String date) {
        return strToDate(date, null);
    }


    /**
     * replateStrN:替换空字符串
     * 
     * @author 陈鹏
     * @param v
     * @return
     */
    public static String replateStrN(String v) {
        return replateStrN(v, "");
    }

    /**
     * replateStrN:用默认字符替换空字符串
     * 
     * @author 陈鹏
     * @param v
     * @return
     */
    public static String replateStrN(String v, String defaultV) {
        if (v == null)
            return defaultV;
        return v;
    }

    /**
     * fenToYuan:分到元 字符文本
     * 
     * @author 陈鹏
     * @param fen
     * @return
     */
    public static String fenToYuan(Integer fen) {
        String value = "0.0";
        if (fen != null) {
            try {
                BigDecimal b1 = new BigDecimal(fen);
                BigDecimal b2 = new BigDecimal(100);
                BigDecimal amount = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);
                value = amount.toPlainString();
            } catch (Exception e) {
            }
        }
        return value;
    }

    /**
     * fmtFee:统计财付通 费率
     * 
     * @author 陈鹏
     * @param v
     * @return
     */
    public static String fmtFee(int v, double j) {

        if (v == 0) {
            return "0";
        }
        BigDecimal b1 = new BigDecimal(v + "");
        BigDecimal b2 = new BigDecimal(100);// 元变分
        BigDecimal b3 = new BigDecimal(j);// 财付通从配置取
        double value = 0;
        try {
            BigDecimal amount = b1.divide(b2).multiply(b3).setScale(2, BigDecimal.ROUND_HALF_UP);
            value = amount.doubleValue();
        } catch (Exception e) {
        }
        // fen = amount.longValue();
        return String.valueOf(value);
    }

    /**
     * toBefore:日期天数偏移, 如果参数为空，则以当前时间为参数
     * 
     * @author 陈鹏
     * @param date
     * @param i 正 当前日期天数加几天;负 当前日期天数减几天
     * @return
     */
    public static Date toOffset(Date date, int i) {

        if (date == null) {
            date = new Date();
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, i);
        return calendar.getTime();
    }

    public static Double stringToDouble(String str) {
        double d = 0.0;
        if (str != null && !"".equals(str)) {
            d = Double.parseDouble(str);
        }
        return d;
    }

    /**
     * 页面显示真实的月
     * 
     * @param date
     * @return
     */
    public static String toTrueMonthDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * toStrRate:商户费率 由万分之几 转到 千分之几
     * 
     * @author 陈鹏
     * @param billRate
     * @return
     */
    public static String toStrRate(Integer billRate) {

        String result = "0.0";
        if (billRate != null) {
            result = billRate / 10.0 + "";
        }
        return result;
    }

    /**
     * toStrRate:商户费率 由万分之几 转到 千分之几
     * 
     * @author 陈鹏
     * @param billRate
     * @param dfValue 设置默认值
     * @return
     */
    public static String toStrRate(Integer billRate, String dfValue) {

        if (billRate == null) {
            return dfValue;
        }
        return toStrRate(billRate);
    }

    public static int getCurrentHour(Date date) {
        if (date == null) {
            date = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 整数相除获取百分比
     * 
     * @param a
     * @param b
     * @return
     */
    public static Integer IntDivisionToInt(Integer a, Integer b) {
        Integer i = 0;
        if (a != null && b != null && b != 0) {
            String s = String.valueOf((double) a / b * 100);
            int isDot = s.indexOf(".");
            if (isDot != -1) {
                i = Integer.parseInt(s.substring(0, isDot));
            }
        }
        return i;
    }

    /**
     * 对象转Integer
     * 
     * @param object
     * @return
     */
    public static Integer nullToInt(Object object) {
        if (object == null) {
            return 0;
        }
        try {
            Integer i = Integer.parseInt(object.toString());
            return i;
        } catch (Exception e) {
            return 0;
        }
    }

    public static Integer toMax(Integer... integers) {
        Integer max = 0;
        for (int i = 0; i < integers.length; i++) {
            if (i == 0) {
                max = integers[i];
            }
            if (max < integers[i]) {
                max = integers[i];
            }
        }
        return max;
    }

    public static Integer toMin(Integer... integers) {
        Integer min = 0;
        for (int i = 0; i < integers.length; i++) {
            if (i == 0) {
                min = integers[i];
            }
            if (min > integers[i]) {
                min = integers[i];
            }
        }
        return min;
    }

    public static String nullToString(Object o) {
        if (o == null) {
            return "";
        }
        return String.valueOf(o).trim();
    }

    /**
     * 对象转Long
     * 
     * @param object
     * @return
     */
    public static Long nullToLong(Object object) {
        if (object == null) {
            return 0L;
        }
        try {
            Long l = Long.parseLong(object.toString());
            return l;
        } catch (Exception e) {
            return 0L;
        }
    }

    /**
     * 对象转Double
     * 
     * @param object
     * @return
     */
    public static Double nullToDouble(Object object) {
        if (object == null) {
            return 0d;
        }
        try {
            Double d = Double.parseDouble(object.toString());
            return d;
        } catch (Exception e) {
            return 0d;
        }
    }

    public static Set<Object> split(String str, String separator) {
        Set<Object> returnSet = new HashSet<Object>();
        if (StringUtils.isNotBlank(str)) {
            String[] strArr = str.split(separator);
            for (String s : strArr) {
                returnSet.add(s);
            }
        }
        return returnSet;
    }

    /**
     * getSecondByDate:根据实际获取 秒数
     * 
     * @param date
     * @return
     */
    public static long getSecondByDate(Date date) {
        if (date != null) {
            return date.getTime() / 1000;
        }
        return 0L;
    }

    public static Long yuanToFen(String applyForRefundMoney) {
        long result = 0;
        try {
            if (StringUtils.isNotBlank(applyForRefundMoney)) {
                BigDecimal bigDecimal = new BigDecimal(applyForRefundMoney);
                BigDecimal jishu = new BigDecimal(100);
                result = bigDecimal.multiply(jishu).longValue();
            }
        } catch (Exception e) {
        }
        return result;
    }

    /**
     * compareDouble:比较double 是否相等
     * 
     * @author chenpeng
     * @param applyForRefundMoney
     * @param d
     * @return
     */
    public static boolean compareDouble(String applyForRefundMoney, double d) {
        Double v = stringToDouble(applyForRefundMoney);
        return Double.compare(v, d) == 0;
    }

    /**
     * getDayBegin:获取当天 起始时间
     * 
     * @author chenpeng
     * @return
     */
    public static Date getDayBegin() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    public static Date getDayEnd() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     * bigAdd:大数据 字符串累加 
     * @author chenpeng
     * @param param1
     * @param param2
     * @return
     */
    public static String bigAdd(String param1, String param2) {

        if (StringUtils.isBlank(param1)) {
            param1 = "0";
        }

        if (StringUtils.isBlank(param2)) {
            param2 = "0";
        }
        BigDecimal result=null;
        
        try {
            BigDecimal bigA = new BigDecimal(param1);
            BigDecimal bigB = new BigDecimal(param2);
            result=   bigA.add(bigB);
            return result.toPlainString();
        } catch (Exception e) {
            
        }
        return  "0";
    }
    
    public static String transSetToString(Set<Object> set, String packStr, String joinStr){
    	if(set == null || set.size() == 0){
    		return null;
    	}
    	StringBuffer str = new StringBuffer();
    	for(Object o : set){
    		str.append(packStr + ToolUtil.nullToString(o) + packStr + joinStr);
    	}
    	if(str.length() > 0){
    		str.deleteCharAt(str.length()-1);
    	}
    	return str.toString();
    }
    
    /**
	 * 
	 * transferFenToYuan:(将分转换成元). <br/>
	 *
	 * @author jiangxl
	 * @param fen
	 * @return
	 */
	public static String transferFenToYuan(String fen) {
		String yuan = "0.00";
		if (StringUtils.isNotBlank(fen)){
            BigDecimal b1 = new BigDecimal(fen);
            BigDecimal b2 = new BigDecimal(YUAN_TO_FEN_RATE);
            BigDecimal amount = b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);
            yuan = amount.toString();
		}
		return yuan;
	}
	
	/**
	 * doubToStr:除去double 小数点后面数字为0
	 * 如：0.0 为 0
	 *   1.0 为1
	 *   3.2为3.2
	 * @author chenpeng
	 * @param dv
	 * @return
	 */
	public static String doubToStr(double dv){
	      String[] vList=(dv+"").split("\\.");
	      if(vList!=null && vList.length==2){
	        int i=Integer.valueOf(vList[1]);
	        if(i>0){
	            return vList[0]+"."+i;
	        }else{
	            return vList[0];
	        }
	      }else if(vList!=null && vList.length==1){
	          return vList[0];
	      }
	      return dv+"";
	}
	
	/**
     * getMchNo:根据订单号获取mchNO 
     * @author chenpeng
     * @param orderNo
     * @return
     */
    public static String getMchNo(String orderNo) {
        String result = "";
        if (StringUtils.isNotBlank(orderNo)) {
            if (orderNo.length() > 18) {
                result = orderNo.substring(0, orderNo.length() - 18);
            }
        }
        return result;
    }
	public static boolean isAllDigital(String str){
		Pattern pattern = Pattern.compile("[0-9]*");
	    Matcher isNum = pattern.matcher(str);
	    if( !isNum.matches() ){
	       return false; 
	    } 
	    return true;
	}
	
	/**
	 * 
	 * @param str
	 * @param maxInteger	整数位数
	 * @param maxDecimal	小数位数
	 * @return
	 */
	public static boolean isFormatDecimal(String str, int maxInteger, int maxDecimal){
		Pattern pattern = Pattern.compile("^\\d" + "{1," + maxInteger +"}(\\.\\d{1," + maxDecimal + "})?$");
	    Matcher isNum = pattern.matcher(str);
	    if( !isNum.matches() ){
	       return false; 
	    } 
	    return true;
	}
	
	
//	public static boolean isThousandFormat(String str){
//		Pattern pattern = Pattern.compile("^\\d+(\\.\\d{1,6})?$"); 
//	    Matcher isNum = pattern.matcher(str);
//	    if( !isNum.matches() ){
//	       return false; 
//	    } 
//	    return true;
//	}
	
	public static String getFormatString(String str, int count, boolean before, String insertStr){
		StringBuffer returnStr = new StringBuffer();
		if(!"".equals(str) && str != null && str.length() > 0){
			if(str.length() > count){
				returnStr.append(str.substring(0, count));
			}else{
				returnStr.append(str);
				for(int i=0;i<count - str.length();i++){
					if(before){
						returnStr.insert(0, insertStr);
					}else{
						returnStr.append(insertStr);
					}
				}
			}
		}else{
			for(int i=0;i<count;i++){
				if(before){
					returnStr.insert(0, insertStr);
				}else{
					returnStr.append(insertStr);
				}
			}
		}
		return returnStr.toString();
	}
	
	public static String getSqlldrString(String str, String separator){
		if(null == str || "".equals(str)){
			return separator;
		}
		return str.trim().replaceAll("\\" + separator, "") + separator;
	}
	
    /**
     * strToDate:日期字符串转换
     * @param date
     * @param format 格式 默认 yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static Date strToDate(String date, String format) {
        if (StringUtils.isBlank(date)) {
            return null;
        }
        if (StringUtils.isBlank(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        try {
            DateFormat dateFormat = new SimpleDateFormat(format);
            return dateFormat.parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * dateToStr:日期转为对应的字符串
     * 
     * @param date
     * @param format 格式 默认 yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String dateToStr(Date date, String format) {
        if (date == null) {
            return "";
        }
        if (StringUtils.isBlank(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        try {
            DateFormat dateFormat = new SimpleDateFormat(format);
            return dateFormat.format(date);
        } catch (Exception e) {
            return "";
        }
    }
    
    /**
     * dateStrToDateStr:日期字符串格式化
     * @param date
     * @param format 格式 默认 yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String dateStrToDateStr(String date, String format) {
        if (date == null) {
            return "";
        }
        if (StringUtils.isBlank(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        try {
        	return dateToStr(strToDate(date, format),format);
        } catch (Exception e) {
            return "";
        }
    }
    
    public static String getChineseCoding(String input){
    	try {
			if(input.equals(new String(input.getBytes("UTF-8"),"UTF-8"))){
				return "UTF-8";
			}
			if(input.equals(new String(input.getBytes("GB2312"),"GB2312"))){
				return "GB2312";
			}
			if(input.equals(new String(input.getBytes("ISO8859_1"),"ISO8859_1"))){
				return "ISO8859_1";
			}
			if(input.equals(new String(input.getBytes("GBK"),"GBK"))){
				return "GBK";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
    }
    
    /**
     * 获取文件的全路径
     * @return
     */
    public static String getFileFullPath(File file){
    	return file.getParent() + File.separator + file.getName();
    }
    
    public static String absStr(String str){
    	if(StringUtils.isBlank(str)){
    		return "0";
    	}
    	return Math.abs(Double.parseDouble(str)) + "";
    }
}
